package com.yanqu.road.server.manger.union;

import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.enums.eMailType;
import com.yanqu.road.entity.enums.eUnionPosition;
import com.yanqu.road.entity.enums.eUnionSyncType;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.enums.*;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.entity.player.UserPatrons;
import com.yanqu.road.entity.union.UnionBaseInfo;
import com.yanqu.road.entity.union.UnionInfo;
import com.yanqu.road.entity.union.UnionMember;
import com.yanqu.road.entity.union.UnionUpgradeInfo;
import com.yanqu.road.entity.union.cross.CrossUnionInfo;
import com.yanqu.road.entity.union.cross.CrossUnionMember;
import com.yanqu.road.entity.union.cross.CrossUnionReward;
import com.yanqu.road.entity.union.cross.CrossUnionServerGroup;
import com.yanqu.road.logic.bussiness.union.cross.CrossUnionBussiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.logic.pb.CrossUnionPb;
import com.yanqu.road.logic.pb.UnionBasePb;
import com.yanqu.road.pb.union.cross.CrossUnionProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.TempServer;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.player.EarnSpeedModule;
import com.yanqu.road.server.logic.mail.MailManager;
import com.yanqu.road.server.manger.CrossUnionServerGroupMgr;
import com.yanqu.road.server.manger.MultipleLanguageMgr;
import com.yanqu.road.server.manger.config.GoodsMgr;
import com.yanqu.road.server.manger.activity.unionwar.UnionPhaseWarMgr;
import com.yanqu.road.server.manger.config.UnionConfigMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.plugin.ManagerReloadListener;
import com.yanqu.road.server.manger.rank.RankMgr;
import com.yanqu.road.server.manger.union.cross.CrossUnionHonorsMgr;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 跨服商会(缓存)
 */
public class CrossUnionMgr extends TempMgr {

    private static Logger logger = LogManager.getLogger(CrossUnionMgr.class.getName());

    private static final Object lockObj = new Object();

    static AtomicLong maxUnionRewardId = new AtomicLong(0);

    //data

    private static Map<String, CrossUnionInfo> unionInfoMap = new ConcurrentHashMap<>();

    private static Map<String, CrossUnionInfo> deleteUnionInfoMap = new ConcurrentHashMap<>();

    private static Map<String, Map<Long, CrossUnionMember>> unionMemberMap = new ConcurrentHashMap<>();

    private static Map<Long, CrossUnionMember> deleteUnionMemberMap = new ConcurrentHashMap<>();

    //是否全量同步过基础数据
    private static volatile boolean allSync;

    /**
     * 与玩家相关的商会奖励（会旗、财富、贡献、经验等）
     */
    static Map<Long, CrossUnionReward> unionRewardMap = new ConcurrentHashMap<>();

    public static List<CrossUnionInfo> getSortUnionList() {
        ArrayList<CrossUnionInfo> crossUnionInfos = new ArrayList<>(unionInfoMap.values());
        crossUnionInfos.sort((o1, o2) -> o2.getTotalEarnSpeed().compareTo(o1.getTotalEarnSpeed()));
        return crossUnionInfos;
    }

    public static List<Long> getUnionMemberIdList(String unionUid) {
        Map<Long, CrossUnionMember> unionMemberMap = getUnionMemberMap(unionUid);
        if (unionMemberMap == null) {
            return new ArrayList<>();
        }
        return new ArrayList<>(unionMemberMap.keySet());
    }

    public static long getUnionServerId(String unionUid) {
        CrossUnionInfo unionInfo = getUnionInfo(unionUid);
        if (unionInfo != null) {
            return unionInfo.getServerId();
        }
        return 0;
    }

    public static Map<Long,Integer> getMemberPositionMap(String unionUid) {
        Map<Long, Integer> map = new HashMap<>();
        Map<Long, CrossUnionMember> unionMemberMap = getUnionMemberMap(unionUid);
        if (unionMemberMap != null) {
            for (CrossUnionMember unionMember : unionMemberMap.values()) {
                map.put(unionMember.getUserId(), unionMember.getPosition());
            }
        }
        return map;
    }

    public static void updateUnionInfo(CrossUnionInfo unionInfo) {
        unionInfoMap.put(unionInfo.getUnionUid(), unionInfo);
    }


    @Override
    public boolean init() throws Exception {
        CrossUnionServerGroupMgr.addReloadListener(new ManagerReloadListener() {
            @Override
            public void notifyReload() {
                syncGroup();
            }
        });
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        long maxRecordId = CrossUnionBussiness.getMaxRewardRecordId();

        Map<Long, CrossUnionReward> unionRewardMapTemp = CrossUnionBussiness.getCrossUnionReward();

        maxUnionRewardId = new AtomicLong(maxRecordId);

        unionRewardMap = unionRewardMapTemp;
        return true;
    }

    @Override
    public boolean stop() {
        return true;
    }

    @Override
    public boolean save() {

        for (Map.Entry<Long, CrossUnionReward> entry : unionRewardMap.entrySet()) {
            CrossUnionReward unionReward = entry.getValue();
            if(unionReward.isInsertOption()){
                CrossUnionBussiness.addCrossUnionReward(unionReward);
            }else if(unionReward.isUpdateOption()){
                CrossUnionBussiness.updateCrossUnionReward(unionReward);
            }
        }
        return true;
    }

    //write
    public static void updateMemberInfo(GamePlayer player, String unionUid) {
        UnionMember unionMember = getUnionMember(unionUid, player.getUserId());
        CrossUnionInfo unionInfo = getUnionInfo(unionUid);
        boolean rankChange = false;
        UserInfo userInfo = player.getUserInfo();
        if (null != unionMember) {
            if (!Objects.equals(unionMember.getUserBaseInfo().getEarnSpeed(), userInfo.getEarnSpeed())) {
                unionMember.setUserBaseInfo(UserMgr.parseUserBaseInfo(userInfo, GameServer.getInstance().getServerId()));
                calcUnionEarnSpeed(unionInfo);
                rankChange = true;
            } else {
                unionMember.setUserBaseInfo(UserMgr.parseUserBaseInfo(userInfo, GameServer.getInstance().getServerId()));
            }
            //resetMemberDailyData(unionMember);
        }

        // 修改家族当前人数
        if (null != unionInfo) {
            synchronized (unionInfo) {
                int memberCount = getUnionMemberCount(unionUid);
                if (unionInfo.getMasterUserId() == player.getUserId()) {
                    if (null != unionMember && unionMember.getPosition() != eUnionPosition.Master.getValue()) {
                        Map<Long, CrossUnionMember> memberMap = getUnionMemberMap(unionUid);
                        if (null != memberMap) {
                            for (UnionMember tempMember : memberMap.values()) {
                                if (tempMember.getPosition() == eUnionPosition.Master.getValue()) {
                                    tempMember.setPosition(eUnionPosition.Member.getValue());
                                }
                            }
                        }
                        unionMember.setPosition(eUnionPosition.Master.getValue());
                    }
                    if (!Objects.equals(userInfo.getNickName(), unionInfo.getMasterNickName())) {
                        unionInfo.setMasterNickName(userInfo.getNickName());
                        rankChange = true;
                    }
                    if (userInfo.getVipExp() != unionInfo.getVipExp()) {
                        unionInfo.setVipExp(userInfo.getVipExp());
                        rankChange = true;
                    }
                    if (!Objects.equals(userInfo.getDecoration(), unionInfo.getDecoration())) {
                        unionInfo.setDecoration(userInfo.getDecoration());
                        rankChange = true;
                    }
                }
                if (unionInfo.getMemberCount() != memberCount) {
                    unionInfo.setMemberCount(memberCount);
                    rankChange = true;
                }
            }
        }
        if (rankChange) {
            //RankMgr.changeUnionRank(unionInfo);
            //UnionActivityMgr.changeUnionInfo(unionInfo);
            //UnionPhaseWarMgr.unionInfoChange(unionInfo);
        }
    }

    public static void playerCheckUnionValid(GamePlayer player) {
        String unionUid = player.getUserInfo().getUnionUid();
        if (!StringUtils.isNullOrEmpty(unionUid)) {
            UnionInfo unionInfo = getUnionInfo(unionUid);
            CrossUnionMember unionMember = getUnionMember(unionUid, player.getUserId());
            int chamberPatronsId = 0;
            if (null == unionInfo || unionInfo.isDelete() || null == unionMember) {
                if (null != unionMember) {
                    chamberPatronsId = unionMember.getChamberPatronsId();
                    unionMember.setUnionUid("");
                    //清除议事厅数据
                    unionMember.setChamberPatronsId(0);
                    //unionMember.setChamberPatron(null);
                    unionMember.setChamberPatrons(null);
                    removeMemberFromMap(unionUid, player.getUserId());
                    addMemberToDeleteMap(unionMember);
                }
                if (null != unionInfo) {
                    synchronized (unionInfo) {
                        if (getUnionMemberCount(unionUid) > 0 && chamberPatronsId > 0) {//商会有人
                            //notifyAllMemberChamberChange(unionUid, player.getUserId(), true, null);
                        } else {//商会没人了
                            unionInfo.setDelete(true);
                        }
                    }
                }
                player.getUserInfo().setUnionUid("");
            }
        }
    }

    public static void addMemberToDeleteMap(CrossUnionMember unionMember) {
        deleteUnionMemberMap.put(unionMember.getUserId(), unionMember);
    }

    public static void addMemberToMap(CrossUnionMember unionMember) {
        if (null == unionMember) {
            return;
        }
        if (!unionMemberMap.containsKey(unionMember.getUnionUid())) {
            unionMemberMap.put(unionMember.getUnionUid(), new ConcurrentHashMap<>());
        }
        unionMemberMap.get(unionMember.getUnionUid()).put(unionMember.getUserId(), unionMember);
    }

    private static void removeMemberFromDeleteMap(long userId) {
        deleteUnionMemberMap.remove(userId);
    }

    private static void removeMemberFromMap(String unionUid, long userId) {
        Map<Long, CrossUnionMember> memberMap = getUnionMemberMap(unionUid);
        if (null != memberMap) {
            memberMap.remove(userId);
        }
    }

    public synchronized static void updateMemberEarnSpeed(GamePlayer player) {
        String unionUid = player.getUserInfo().getUnionUid();
        if (StringUtils.isNullOrEmpty(unionUid)) {
            return;
        }
        UnionMember unionMember = getUnionMember(unionUid, player.getUserId());
        CrossUnionInfo unionInfo = getUnionInfo(unionUid);
        if (null != unionMember) {
            BigInteger earnSpeed = player.getModule(EarnSpeedModule.class).getEarnSpeed();
            if (!Objects.equals(unionMember.getUserBaseInfo().getEarnSpeed(), earnSpeed)) {
                unionMember.setUserBaseInfo(UserMgr.parseUserBaseInfo(player.getUserInfo(), GameServer.getInstance().getServerId()));
                calcUnionEarnSpeed(unionInfo);
                RankMgr.changeUnionRank(unionInfo);
            }
        }
    }

    private static void calcUnionEarnSpeed(CrossUnionInfo unionInfo) {
        if (null == unionInfo) {
            return;
        }
        Map<Long, CrossUnionMember> memberMap = getUnionMemberMap(unionInfo.getUnionUid());
        BigInteger totalEarnSpeed = BigInteger.ZERO;
        if (null != memberMap) {
            for (UnionMember unionMember : memberMap.values()) {
                totalEarnSpeed = totalEarnSpeed.add(unionMember.getUserBaseInfo().getEarnSpeed());
            }
        }
        unionInfo.setTotalEarnSpeed(totalEarnSpeed);
        if(unionInfo.isCross()){
            UnionPhaseWarMgr.unionInfoChange(unionInfo);
        }
    }

    public static void sendFirstJoinReward(UserInfo userInfo) {
        TempServer.getTimerExecutorService().execute(() -> {
            try {
                MailManager.sendMail(userInfo.getUserId(), eMailType.SYSTEM.getValue(), PropertyHelper.parseGoodsToString(GameConfig.GAME_MONEY_INGOTS,
                        BigInteger.valueOf(GameConfig.UNION_FIRST_JOIN_REWARD)), MultipleLanguageMgr.getContent(MailManager.UNION_FIRST_JOIN_CONTENT, userInfo.getLanguage()),
                        MultipleLanguageMgr.getContent(MailManager.UNION_FIRST_JOIN_TITLE, userInfo.getLanguage()));
            } catch (Exception e) {
                logger.error(e);
            }
        });
    }


    public static void notifySameNicknameCount(UnionInfo unionInfo) {
        if (null != unionInfo) {
            Map<Long, CrossUnionMember> memberMap = getUnionMemberMap(unionInfo.getUnionUid());
            if (null != memberMap) {
                int memberCount = getSameNicknameCount(unionInfo);
                for (CrossUnionMember member : memberMap.values()) {
                    if(member.getServerId() != GameServer.getInstance().getServerId()){
                        continue;
                    }
                    GamePlayer player = GamePlayerMgr.getOnlinePlayer(member.getUserId());
                    if (null != player) {
                        player.notifyListener(eGamePlayerEventType.UnionSameNickname.getValue(), memberCount);
                    }
                }
            }
        }
    }

    public static void userPatronDispatchSkillChangeNotify(String unionUid, long userId, UserPatrons userPatrons){
        if(!StringUtils.isNullOrEmpty(unionUid)) {
            UnionInfo unionInfo = CrossUnionMgr.getUnionInfo(unionUid);
            CrossUnionMember unionMember = CrossUnionMgr.getUnionMember(unionUid, userId);
            if(null != unionInfo && null != unionMember && unionMember.getChamberPatronsId() == userPatrons.getPatronsId()) {
                CrossUnionProto.UnionChamberDispatchCrossReqMsg.Builder crossReq = CrossUnionProto.UnionChamberDispatchCrossReqMsg.newBuilder();
                crossReq.setPatrons(CrossUnionPb.buildCrossUnionChamberPatronsTemp(userPatrons));
                crossReq.setPatronsId(userPatrons.getPatronsId());
                crossReq.setNeedBack(false);
                GamePlayerMgr.sendPacket(userId, YanQuMessageUtils.buildMessage(Protocol.C_UNION_CHAMBER_DISPATCH, crossReq));
            }
        }
    }

    //read

    public static int getUnionMemberCount(String unionUid) {
        Map<Long, CrossUnionMember> memberMap = getUnionMemberMap(unionUid);
        if (null != memberMap) {
            return memberMap.size();
        }
        return 0;
    }

    public static int getSameNicknameCount(UnionInfo unionInfo) {
        int count = 0;
        UnionMember master = getMasterUnionMember(unionInfo.getUnionUid());
        if (master == null) {
            return 0;
        }
        String masterNickName = master.getUserBaseInfo().getNickName().trim();
        String startName = masterNickName.substring(0, 2);
        String endName = masterNickName.substring(masterNickName.length() - 2, masterNickName.length());
        Map<Long, CrossUnionMember> unionMemberMap = getUnionMemberMap(unionInfo.getUnionUid());
        for (UnionMember member : unionMemberMap.values()) {
//            if(member.getPosition() != eUnionPosition.Master.getValue()){
            if (member.getUserBaseInfo().getNickName().trim().indexOf(startName) >= 0 || member.getUserBaseInfo().getNickName().trim().indexOf(endName) >= 0) {
                count++;
            }
//            }
        }
        return count;
    }

    private static UnionMember getMasterUnionMember(String unionUid) {
        UnionInfo unionInfo = getUnionInfo(unionUid);
        if (null == unionInfo) {
            return null;
        }
        Map<Long, CrossUnionMember> memberMap = getUnionMemberMap(unionUid);
        if (null != memberMap) {
            UnionMember masterMember = memberMap.get(unionInfo.getMasterUserId());
            if (null == masterMember) {
                return null;
            }
            if (masterMember.getPosition() != eUnionPosition.Master.getValue()) {
                for (UnionMember unionMember : memberMap.values()) {
                    if (unionMember.getPosition() == eUnionPosition.Master.getValue()) {
                        unionMember.setPosition(eUnionPosition.Member.getValue());
                    }
                }
                masterMember.setPosition(eUnionPosition.Master.getValue());
            }
            return masterMember;
        }
        return null;
    }

    public static CrossUnionInfo getUnionInfo(String unionUid) {
        return unionInfoMap.get(unionUid);
    }

    public static Map<Long, CrossUnionMember> getUnionMemberMap(String unionUid) {
        Map<Long, CrossUnionMember> resultMap = new HashMap<>();
        Map<Long, CrossUnionMember> memberMap = unionMemberMap.get(unionUid);
        if (memberMap == null) {
            return resultMap;
        }else{
            resultMap.putAll(memberMap);
        }
        return resultMap;
    }

    public static Object getLockObj() {
        return lockObj;
    }

    public static String getUnionName(String unionUid) {
        UnionInfo unionInfo = getUnionInfo(unionUid);
        if (unionInfo != null) {
            return unionInfo.getUnionName();
        }
        return "";
    }

    public static CrossUnionMember getUnionMember(long userId) {
        CrossUnionMember unionMember;
        for (Map<Long, CrossUnionMember> memberMap : unionMemberMap.values()) {
            unionMember = memberMap.get(userId);
            if (null != unionMember) {
                return unionMember;
            }
        }
        return null;
    }

    public static CrossUnionMember getUnionMember(String unionUid, long userId) {
        if (!StringUtils.isNullOrEmpty(unionUid)) {
            Map<Long, CrossUnionMember> memberMap = getUnionMemberMap(unionUid);
            if (null != memberMap) {
                return memberMap.get(userId);
            }
            return null;
        } else {
            return deleteUnionMemberMap.get(userId);
        }
    }

    public static int getUnionMaxMemberSize(String unionUid) {
        CrossUnionInfo unionInfo = getUnionInfo(unionUid);
        if (unionInfo == null) {
            return 0;
        }
        return UnionConfigMgr.getMaxMemberCount(unionInfo.getExperience(), unionInfo.isCross(), CrossUnionServerGroupMgr.getGroupServerCountByServerId(unionInfo.getServerId()));
    }

    public static boolean isSameUnion(long userId1, long userId2) {
        UserInfo userInfo1 = UserMgr.getUserInfo(userId1);
        UserInfo userInfo2 = UserMgr.getUserInfo(userId2);
        if (userInfo1 != null && userInfo2 != null) {
            if (!StringUtils.isNullOrEmpty(userInfo1.getUnionUid()) && userInfo1.getUnionUid().equals(userInfo2.getUnionUid())) {
                return true;
            }
        }
        return false;
    }

    public static long getUnionAliasId(String unionUid) {
        UnionInfo unionInfo = getUnionInfo(unionUid);
        if (unionInfo != null) {
            return unionInfo.getUnionAliasId();
        }
        return 0;
    }

    public static boolean crossGroupOpen(){
        CrossUnionServerGroup group = CrossUnionServerGroupMgr.getServerGroupByServerId(GameServer.getInstance().getServerId());
        return group != null && group.getState() == 1;
    }

    public static CrossUnionInfo getGroupRankTop(){
        int groupId = CrossUnionServerGroupMgr.getGroupIdByServerId(GameServer.getInstance().getServerId());
        Set<Long> serverIdSet = CrossUnionServerGroupMgr.getGroupServer(groupId);
        List<CrossUnionInfo> list = new ArrayList<>();
        for (Map.Entry<String, CrossUnionInfo> entry : CrossUnionMgr.getUnionInfoMap().entrySet()) {
            if(entry.getValue().isDelete()){
                continue;
            }
            if(serverIdSet.contains(entry.getValue().getServerId())){
                list.add(entry.getValue());
            }
        }
        list.sort(new Comparator<CrossUnionInfo>() {
            @Override
            public int compare(CrossUnionInfo o1, CrossUnionInfo o2) {
                return o2.getTotalEarnSpeed().compareTo(o1.getTotalEarnSpeed());
            }
        });
        if(list.size() > 0){
            return list.get(0);
        }
        return null;
    }

    //set   get

    public static Map<String, CrossUnionInfo> getUnionInfoMap() {
        return unionInfoMap;
    }

    public static void setUnionInfoMap(Map<String, CrossUnionInfo> unionInfoMap) {
        CrossUnionMgr.unionInfoMap = unionInfoMap;
    }

    public static Map<String, CrossUnionInfo> getDeleteUnionInfoMap() {
        return deleteUnionInfoMap;
    }

    public static void setDeleteUnionInfoMap(Map<String, CrossUnionInfo> deleteUnionInfoMap) {
        CrossUnionMgr.deleteUnionInfoMap = deleteUnionInfoMap;
    }

    public static Map<String, Map<Long, CrossUnionMember>> getUnionMemberMap() {
        return unionMemberMap;
    }

    public static void setUnionMemberMap(Map<String, Map<Long, CrossUnionMember>> unionMemberMap) {
        CrossUnionMgr.unionMemberMap = unionMemberMap;
    }

    public static Map<Long, CrossUnionMember> getDeleteUnionMemberMap() {
        return deleteUnionMemberMap;
    }

    public static void setDeleteUnionMemberMap(Map<Long, CrossUnionMember> deleteUnionMemberMap) {
        CrossUnionMgr.deleteUnionMemberMap = deleteUnionMemberMap;
    }

    public static Map<Long, CrossUnionReward> getUnionRewardMap() {
        return unionRewardMap;
    }

    public static Logger getLogger() {
        return logger;
    }

    public static void setAllSync(boolean allSync) {
        CrossUnionMgr.allSync = allSync;
    }

    public static boolean isAllSync() {
        return allSync;
    }

    //sync
    public static void fetchCrossData() {
        if(!allSync){
            GamePlayerMgr.sendPacket(0, YanQuMessageUtils.buildMessage(Protocol.C_CROSS_UNION_REQUEST_ALL_BASE_DATA, CrossUnionProto.RequestCrossUnionDataReqMsg.newBuilder()));
        }
    }

    public static void update(int syncType, CrossUnionInfo unionInfo, Map<Long, CrossUnionMember> memberMap, CrossUnionMember changeMember) {
        if(syncType == eUnionSyncType.DeleteUnion.getValue()){
            unionInfoMap.remove(unionInfo.getUnionUid());
            deleteUnionInfoMap.put(unionInfo.getUnionUid(), unionInfo);
            unionMemberMap.remove(unionInfo.getUnionUid());
            deleteUnionMemberMap.putAll(memberMap);
        }else {
            unionInfoMap.put(unionInfo.getUnionUid(), unionInfo);

            if(changeMember != null){
                if(syncType == eUnionSyncType.JoinUnion.getValue() || syncType == eUnionSyncType.CreateUnion.getValue()){
                    deleteUnionMemberMap.remove(changeMember.getUserId());
                }
                if(syncType == eUnionSyncType.QuitUnion.getValue() || syncType == eUnionSyncType.BeKick.getValue()){
                    addMemberToDeleteMap(changeMember);
                }
            }

            unionMemberMap.put(unionInfo.getUnionUid(), memberMap);
        }
    }

    public static void addReward(UserInfo userInfo, int goodsId, long num, int son, int type) {
        String unionUid = userInfo.getUnionUid();

        CrossUnionReward unionReward = new CrossUnionReward();
        unionReward.setRecordId(maxUnionRewardId.incrementAndGet());
        unionReward.setUserId(userInfo.getUserId());
        unionReward.setUnionUid(unionUid);
        unionReward.setReward(goodsId + "=" + num);
        unionReward.setSon(son);
        unionReward.setAddTime(DateHelper.getCurrentSecond());
        unionReward.setType(type);
        unionReward.setInsertOption();

        synchronized (unionRewardMap){
            unionRewardMap.put(unionReward.getRecordId(), unionReward);
        }

        uploadUnionReward(unionReward);
    }

    //商会奖励补发的时候剔除掉荣誉奖励道具id
    public static String removeHonourItem(String rewardStr){
        Property reward = PropertyHelper.parseStringToProperty(rewardStr);
        List<Integer> goodsIdList = new ArrayList<>(reward.getGoods().keySet());
        for(int goodsId : goodsIdList){
            if(GoodsMgr.isHonorScore(goodsId)){
                reward.removeProperty(goodsId);
            }
        }
        return PropertyHelper.parsePropertyToString(reward);
    }

    //领取商会奖励会长奖励的时候的荣誉点道具
    public static void getRewardHonourItem(String rewardStr, ActivityInfo activityInfo,int rank,String unionId,long userId){
        if(StringUtils.isNullOrEmpty(rewardStr) || StringUtils.isNullOrEmpty(unionId)){
            return ;
        }
        Property reward = PropertyHelper.parseStringToProperty(rewardStr);
        Map<Integer, BigInteger> goodMap = reward.getGoods();
        for(int goodsId : goodMap.keySet()){
            long num = goodMap.get(goodsId).longValue();
            if(GoodsMgr.isHonorScore(goodsId) && num > 0){
//                addRewardHonourItem(userId,unionId,goodsId,num,eLogMoneyType.Activity.getValue(),eLogMoneyType.ActivityReward.getValue());
                CrossUnionHonorsMgr.addHonorsItemRecord(
                        activityInfo.getActivityId(),
                        activityInfo.getType(),
                        activityInfo.getChildType(),
                        rank,
                        userId,
                        unionId,
                        num,
                        activityInfo.getServerIdList(),
                        goodsId
                );
            }
        }
    }

    /*public static void addRewardHonourItem(long userId,String unionId, int goodsId, long num, int son, int type) {
        CrossUnionReward unionReward = new CrossUnionReward();
        unionReward.setRecordId(maxUnionRewardId.incrementAndGet());
        unionReward.setUserId(userId);
        unionReward.setUnionUid(unionId);
        unionReward.setReward(goodsId + "=" + num);
        unionReward.setSon(son);
        unionReward.setAddTime(DateHelper.getCurrentSecond());
        unionReward.setType(type);
        unionReward.setInsertOption();

        synchronized (unionRewardMap){
            unionRewardMap.put(unionReward.getRecordId(), unionReward);
        }

        uploadUnionReward(unionReward);
    }*/

    public static void uploadUnionReward(CrossUnionReward unionReward) {
        if(!StringUtils.isNullOrEmpty(unionReward.getUnionUid())) {
            CrossUnionProto.CrossUnionUploadRewardReqMsg.Builder msg = CrossUnionProto.CrossUnionUploadRewardReqMsg.newBuilder();
            CrossUnionProto.CrossUnionRewardTemp.Builder builder = CrossUnionProto.CrossUnionRewardTemp.newBuilder();
            builder.setRecordId(unionReward.getRecordId());
            builder.setUnionUid(unionReward.getUnionUid());
            builder.setReward(unionReward.getReward());
            builder.setUserId(unionReward.getUserId());
            builder.setType(unionReward.getType());
            builder.setSon(unionReward.getSon());
            msg.addReward(builder);
            GamePlayerMgr.sendPacket(0, YanQuMessageUtils.buildMessage(Protocol.C_UNION_UPLOAD_REWARD, msg));
        }
    }

    public static UnionBaseInfo parseUnionBaseInfo(String unionId){
        CrossUnionInfo unionInfo = getUnionInfo(unionId);
        if(null == unionInfo){
            return null;
        }
        UnionBaseInfo baseInfo = new UnionBaseInfo();
        baseInfo.setUnionAliasId(unionInfo.getUnionAliasId());
        baseInfo.setUnionName(unionInfo.getUnionName());
        baseInfo.setUnionFlag(unionInfo.getUnionFlag());
        baseInfo.setExperience(unionInfo.getExperience());
        baseInfo.setMemberCount(unionInfo.getMemberCount());
        baseInfo.setAllowRandomJoin(unionInfo.isAllowRandomJoin());
        baseInfo.setTotalEarnSpeed(unionInfo.getTotalEarnSpeed());
        baseInfo.setMasterUserId(unionInfo.getMasterUserId());
        baseInfo.setMasterNickName(unionInfo.getMasterNickName());
        baseInfo.setMasterVipExp(unionInfo.getVipExp());
        baseInfo.setMasterDecoration(unionInfo.getDecoration());
        baseInfo.setServerId(unionInfo.getServerId());
        baseInfo.setCross(unionInfo.isCross());
        baseInfo.setUnionFlagStr(unionInfo.getUnionFlagStr());
        baseInfo.setHonors(unionInfo.getHonors());
        Map<Long, CrossUnionMember> unionMemberMap = new HashMap<>(getUnionMemberMap(unionId));
        for (CrossUnionMember unionMember : unionMemberMap.values()) {
            if (unionMember.getPosition() == eUnionPosition.Master.getValue()) {
                UserBaseInfo userBaseInfo = unionMember.getUserBaseInfo();
                baseInfo.setHideVipAndAddress(userBaseInfo.getHideVipAndAddress());
                baseInfo.setSex(userBaseInfo.getSex());
                baseInfo.setMasterVipExp(userBaseInfo.getVipExp());
                baseInfo.setMasterDecoration(userBaseInfo.getDecoration());
                baseInfo.setMasterNickName(userBaseInfo.getNickName());
            }
        }
        return baseInfo;
    }


    public static List<CrossUnionInfo> getUnionListInServer(long serverId){
        List<CrossUnionInfo> list = new ArrayList<>();
        for (CrossUnionInfo unionInfo : unionInfoMap.values()) {
            if(unionInfo.isDelete()){
                continue;
            }
            if(serverId == unionInfo.getServerId()){
                list.add(unionInfo);
            }
        }
        return list;
    }

    public static UnionBaseInfo parseUnionBaseInfo(CrossUnionInfo unionInfo){
        UnionBaseInfo baseInfo = new UnionBaseInfo();
        baseInfo.setUnionAliasId(unionInfo.getUnionAliasId());
        baseInfo.setUnionName(unionInfo.getUnionName());
        baseInfo.setUnionFlag(unionInfo.getUnionFlag());
        baseInfo.setExperience(unionInfo.getExperience());
        baseInfo.setMemberCount(unionInfo.getMemberCount());
        baseInfo.setAllowRandomJoin(unionInfo.isAllowRandomJoin());
        baseInfo.setTotalEarnSpeed(unionInfo.getTotalEarnSpeed());
        baseInfo.setTotalPatronsAbility(unionInfo.getTotalMaxAbility());
        baseInfo.setMasterUserId(unionInfo.getMasterUserId());
        baseInfo.setMasterNickName(unionInfo.getMasterNickName());
        baseInfo.setMasterVipExp(unionInfo.getVipExp());
        baseInfo.setMasterDecoration(unionInfo.getDecoration());
        baseInfo.setServerId(unionInfo.getServerId());
        baseInfo.setCross(unionInfo.isCross());
        baseInfo.setUnionFlagStr(unionInfo.getUnionFlagStr());
        baseInfo.setHonors(unionInfo.getHonors());
        Map<Long, CrossUnionMember> unionMemberMap = new HashMap<>(getUnionMemberMap(unionInfo.getUnionUid()));
        for (CrossUnionMember unionMember : unionMemberMap.values()) {
            if (unionMember.getPosition() == eUnionPosition.Master.getValue()) {
                UserBaseInfo userBaseInfo = unionMember.getUserBaseInfo();
                baseInfo.setHideVipAndAddress(userBaseInfo.getHideVipAndAddress());
                baseInfo.setSex(userBaseInfo.getSex());
                baseInfo.setMasterVipExp(userBaseInfo.getVipExp());
                baseInfo.setMasterDecoration(userBaseInfo.getDecoration());
                baseInfo.setMasterNickName(userBaseInfo.getNickName());
            }
        }
        return baseInfo;
    }

    //build

    public static CrossUnionProto.UnionServerGroupSyncMsg.Builder buildCrossUnionGroup(CrossUnionServerGroup serverGroup) {
        CrossUnionProto.UnionServerGroupSyncMsg.Builder syncMsg = CrossUnionProto.UnionServerGroupSyncMsg.newBuilder();
        if(serverGroup == null){
            syncMsg.setCrossOpen(false);
        }else {
            syncMsg.setCrossOpen(serverGroup.getState() == 1);
            syncMsg.setGroupId(serverGroup.getGroupId());
            syncMsg.addAllServerList(new ArrayList<>(serverGroup.getServerList()));
        }
        return syncMsg;
    }

    private static void syncGroup() {

        CrossUnionServerGroup serverGroup = CrossUnionServerGroupMgr.getServerGroupByServerId(GameServer.getInstance().getServerId());
        for (GamePlayer player : GamePlayerMgr.getCopyPlayerList()) {
            CrossUnionProto.UnionServerGroupSyncMsg.Builder syncMsg = CrossUnionMgr.buildCrossUnionGroup(serverGroup);
            player.sendPacket(Protocol.U_UNION_CROSS_GROUP_SYNC, syncMsg);
        }

    }

    public static List<Long> getUnionMemberIdListByZeroAbilityAndOwnServer() {
        List<Long> userIdList = new ArrayList<>();
        unionMemberMap.forEach((unionUid, longCrossUnionMemberMap) -> {
            longCrossUnionMemberMap.forEach((memberId, crossUnionMember) -> {
                if (crossUnionMember.getServerId() == GameServer.getInstance().getServerId() && crossUnionMember.getHistoryMaxAbility().equals(BigInteger.ZERO)) {
                    userIdList.add(crossUnionMember.getUserId());
                }
            });
        });

        deleteUnionMemberMap.values().forEach(crossUnionMember -> {
            if (crossUnionMember.getServerId() == GameServer.getInstance().getServerId() && crossUnionMember.getHistoryMaxAbility().equals(BigInteger.ZERO)) {
                userIdList.add(crossUnionMember.getUserId());
            }
        });
        return userIdList;
    }

    public static List<CrossUnionInfo> getTopUnionListByServerId(int topCount, long serverId) {
        List<CrossUnionInfo> unionInfos = new ArrayList<>();
        for (CrossUnionInfo unionInfo : unionInfoMap.values()) {
            if (unionInfo.isDelete()) {
                continue;
            }
            if (unionInfo.getServerId() != serverId) {
                continue;
            }

            BigInteger totalAbility = BigInteger.ZERO;
            Map<Long, CrossUnionMember> memberMap = getUnionMemberMap(unionInfo.getUnionUid());
            for (CrossUnionMember crossUnionMember : memberMap.values()) {
                totalAbility = totalAbility.add(crossUnionMember.getHistoryMaxAbility());
            }
            unionInfo.setTotalMaxAbility(totalAbility);
            unionInfos.add(unionInfo);
        }
        unionInfos.sort((o1, o2) -> {
            return o2.getTotalMaxAbility().compareTo(o1.getTotalMaxAbility());
        });

        List<CrossUnionInfo> unionInfoList = new ArrayList<>();
        for (int i = 0; i < topCount && i < unionInfos.size(); i++) {
            CrossUnionInfo unionInfo = unionInfos.get(i);
            unionInfoList.add(unionInfo);
        }
        return unionInfoList;
    }

    public static List<Long> getTopUnionMemberListByServerId(int topCount, long serverId) {
        List<Long> memberIds = new ArrayList<>();
        List<CrossUnionInfo> unionInfos = getTopUnionListByServerId(topCount, serverId);
        for (CrossUnionInfo unionInfo : unionInfos) {
            memberIds.addAll(getUnionMemberIdList(unionInfo.getUnionUid()));
        }
        return memberIds;
    }
}
